package model.BD;



import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import model.utils.Configuracion;


public class BasedeDatos {
	private Connection conexion;
	private static String bd;
	private static String user;
	private static String password;
	private static String host;
	private static String port;
	private static String server;
	private static BasedeDatos basedeDatos;
	
	/** Creates a new instance of BasedeDatos */
	private BasedeDatos() {
		try {
			Properties props = Configuracion.obtenerArchivoPropiedades("config.properties");
			this.bd = props.getProperty("schema");
			this.user = props.getProperty("user");
			this.password = props.getProperty("password");
			this.host = props.getProperty("host");
			this.port = props.getProperty("port");
			this.server = String.format("jdbc:mysql://%s:%s/%s", this.host, this.port,this.bd);
			
		} catch (FileNotFoundException e) {
			System.out.println("Error levantando archivo de configuracion");
			e.printStackTrace();
		}
		
	}
	
	public static BasedeDatos obtenerInstancia() {
		if(basedeDatos == null) {
			basedeDatos = new BasedeDatos();
			return basedeDatos;
		} else {
			return basedeDatos;
		}
	}

	public void establecerConexion() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conexion = DriverManager.getConnection(server, user, password);
		} catch (Exception e) {
			System.out.println("Imposible realizar conexion con la BD");
			e.printStackTrace();
		}
	}

	public Connection getConexion() {
		return conexion;
	}

	public void cerrar(ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (Exception e) {
				System.out.print("No es posible cerrar la Conexion");
			}
		}
	}

	public void cerrar(java.sql.Statement stmt) {
		if (stmt != null) {
			try {
				stmt.close();
			} catch (Exception e) {
			}
		}
	}

	public void destruir() {

		if (conexion != null) {

			try {
				conexion.close();
				conexion = null;
			} catch (Exception e) {
			}
		}
	}

	public ResultSet runStatement(String query) {
		Statement stmt;
		try {
			stmt = this.conexion.createStatement();

			ResultSet rs = stmt.executeQuery(query);
			
			return rs;
		} catch (SQLException e) {
			System.out.println("Error ejecutando query: " + e.getMessage());
		}
		return null;
	}
	
	public ResultSet runPreparedStatement(PreparedStatement stmt) {
		
		try {

			ResultSet rs = stmt.executeQuery();
			
			return rs;
		} catch (SQLException e) {
			System.out.println("Error ejecutando query: " + e.getMessage());
		}
		return null;
	}

}
